package com.tuomaxu.controller;

import com.tuomaxu.pojo.User;
import com.tuomaxu.service.IDCodeService;
import com.tuomaxu.service.impl.UserServiceImpl;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserServiceImpl userService;

    @Reference
    private IDCodeService codeService;

    /**
     * /user/register/{email}/{password}/{code}
     * http://localhost:8080/api/user/register/123@qq.com/1234/1234
     */
    @GetMapping("/register/{email}/{password}/{code}")
    public Integer register(@PathVariable String email, @PathVariable String password, @PathVariable String code, HttpServletResponse response){
        //首先调用code微服务验证email和code

        Integer validate = codeService.validate(email, code);
        if(validate != 0){
            //1错误  2超时
            return validate;
        }

        User user = new User();
        user.setEmail(email);
        user.setPassword(password);
        String token = UUID.randomUUID().toString();
        user.setToken(token);
        //将token写入cookie

        if(userService.addUser(user) == false){
            //数据库错误
            return 3;
        }
        Cookie cookie = new Cookie("token",token);
        response.addCookie(cookie);

        return 0;
    }



    /**
     * /user/login/{email}/{password}
     * 登录接⼝口，验证⽤用户名密码合法性，
     * 根据⽤用户名和 密码⽣生成token，token存⼊入数据库，并写⼊入cookie 中，
     * 登录成功返回邮箱地址，重定向到欢迎⻚页
     */
    @GetMapping("/login/{email}/{password}")
    public String login(@PathVariable String email,@PathVariable String password,HttpServletResponse response){
        boolean b = userService.isRegistered(email);
        if(!b){
            return "";
        }
        User user = userService.findUser(email, password);
        if(user == null){
            return "";
        }
        String token = UUID.randomUUID().toString();
        user.setToken(token);
        userService.updateToken(user);
        Cookie cookie = new Cookie("token",token);
        response.addCookie(cookie);
        return user.getToken();
    }

    @GetMapping("/info/{token}")
    public String info(@PathVariable String token,HttpServletResponse response){
        User user = userService.findUserByToken(token);
        return user.getEmail();
    }


}
